//
//  MZRecommendThirdViewController.m
//  OurTourism
//
//  Created by 孟镇 on 15/11/27.
//  Copyright © 2015年 Devil_Coming. All rights reserved.
//

#import "MZRecommendThirdViewController.h"
#import "Header.h"
#import "MZRecommendPushCollectionViewCell.h"
#import "MZRecommendPushCollectionReusableView.h"
#import "MZRecommendModel.h"
#import "MZRecommendLastViewController.h"
#import "MZRecommendPhotosViewController.h"
#import "MZNiceNotesViewController.h"
#import "CoreDataManager.h"
#import "MuDiDi.h"
#import "landingViewController.h"

@interface MZRecommendThirdViewController () <UICollectionViewDataSource, UICollectionViewDelegate>

@property(nonatomic, strong) UIView *naviView;
@property(nonatomic, strong) UILabel *naviLabel;
@property(nonatomic, strong) UICollectionView *collectionView;
@property(nonatomic, strong) NSMutableArray *dataArr;
@property(nonatomic, strong) MBProgressHUD *HUB;
@property(nonatomic, strong) NSDictionary *dataDic;
@property(nonatomic, retain) UIImageView *backImg;
@property(nonatomic, retain) UILabel *countryLabel; //国家名
@property(nonatomic, retain) UILabel *goCount; //去过人数
@property(nonatomic, retain) UIImageView *img; //渐变色图片
@property(nonatomic, strong) UIImageView *topJianBian;
@property(nonatomic, strong) UIImageView *camearImg;
@property(nonatomic, strong) UILabel *photoCountLabel;

@property(nonatomic, strong) CoreDataManager *manager;
@property(nonatomic, strong) UIButton *likeBtn;
@property(nonatomic, assign) BOOL isLake; // 判断是否收藏
@property(nonatomic, strong) NSMutableArray *coreDataArr;

@property(nonatomic, strong) UIButton *shareBtn;
@end

@implementation MZRecommendThirdViewController
- (void)dealloc
{
    [UMSocialShakeService unShakeToSns];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithRed:250 / 255. green:246 / 255. blue:232 / 255. alpha:1];
    
    self.dataArr = [NSMutableArray array];
    self.coreDataArr = [NSMutableArray array];
    
    [self prepareData];
    [self createCollectionView];
    
    self.HUB = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.HUB show:YES];
    self.HUB.labelText = @"正在加载";
    
    self.naviView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 64)];
    self.naviView.backgroundColor = [UIColor colorWithRed:62 / 255. green:176 / 255. blue:192 / 255. alpha:1];
    self.naviView.alpha = 0;
    [self.view addSubview:self.naviView];
    
    self.naviLabel = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH / 2 - 100, 25, 200, 25)];
    self.naviLabel.textColor = [UIColor whiteColor];
    self.naviLabel.textAlignment = NSTextAlignmentCenter;
    self.naviLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:19];
    self.naviLabel.text = self.tempModel.name;
    [self.naviView addSubview:self.naviLabel];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(10, 25, 25, 25);
    [backBtn setImage:[UIImage imageNamed:@"iconfont-iconfonticonfontjiantouzuo11@2x"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
    
    self.likeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.likeBtn.frame = CGRectMake(WIDTH - 100, 20, 25, 25);
    [self.likeBtn addTarget:self action:@selector(likeAction:) forControlEvents:UIControlEventTouchUpInside];
    self.likeBtn.hidden = YES;
    [self.view addSubview:self.likeBtn];
    
    //分享按钮
    self.shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.shareBtn.frame = CGRectMake(WIDTH - 50, 15, 30, 30);
    [self.shareBtn addTarget:self action:@selector(shareAction) forControlEvents:UIControlEventTouchUpInside];
    [self.shareBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-fenxiang"] forState:UIControlStateNormal];
    [self.view addSubview:self.shareBtn];
    self.shareBtn.hidden = YES;
    
    self.manager = [CoreDataManager shareInstance];
    //    NSLog(@"%@", [self.manager applicationDocumentsDirectory]);
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"MuDiDi" inManagedObjectContext:self.manager.managedObjectContext];
    [fetchRequest setEntity:entity];
    NSArray *fetchedObjects = [self.manager.managedObjectContext executeFetchRequest:fetchRequest error:nil];
    if (fetchedObjects.count == 0) {
        
        [self.likeBtn setBackgroundImage:[UIImage imageNamed:@"whiteHeart"] forState:UIControlStateNormal];
    }else{
        
        self.coreDataArr = [NSMutableArray arrayWithArray:fetchedObjects];
        for (MuDiDi *model in self.coreDataArr) {
            
            if ([model.name isEqualToString:self.tempModel.name]) {
                
                self.isLake = YES;
                break;
            }
        }
        
        if (self.isLake == NO) {
            
            [self.likeBtn setBackgroundImage:[UIImage imageNamed:@"whiteHeart"] forState:UIControlStateNormal];
            
        }else{
            
            [self.likeBtn setBackgroundImage:[UIImage imageNamed:@"redHeart"] forState:UIControlStateNormal];
            
        }
        
    }
    
    //摇一摇分享
    [UMSocialShakeService setShakeToShareWithTypes:@[UMShareToSina,UMShareToTencent,UMShareToQzone,UMShareToRenren,UMShareToDouban]
                                         shareText:[NSString stringWithFormat:@"「%@」\nhttp://web.breadtrip.com/scenic/%@/%@/",self.tempModel.name, self.tempModel.type, self.tempModel.valueId]
                                      screenShoter:[UMSocialScreenShoterDefault screenShoter]
                                  inViewController:self
                                          delegate:nil];
    [UMSocialShakeService setShakeThreshold:1.5];
}


#pragma mark - 创建collectionView
- (void)createCollectionView
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake((WIDTH - 30) / 2, (WIDTH - 30) / 2);
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    layout.headerReferenceSize = CGSizeMake(WIDTH, 20 + (WIDTH - 15) / 4);
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGTH + 50) collectionViewLayout:layout];
    self.collectionView.backgroundColor = [UIColor colorWithRed:250 / 255. green:246 / 255. blue:232 / 255. alpha:1];
    self.collectionView.contentInset = UIEdgeInsetsMake(HEIGTH / 4 + 20, 0, 0, 0);
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.alwaysBounceVertical = YES;
    [self.view addSubview:self.collectionView];
    [self.collectionView registerClass:[MZRecommendPushCollectionViewCell class] forCellWithReuseIdentifier:@"destinationPush"];
    [self.collectionView registerClass:[MZRecommendPushCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    
    self.backImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, -HEIGTH / 4 - 40, WIDTH, HEIGTH / 4 + 40)];
    self.backImg.contentMode = UIViewContentModeScaleAspectFill;//设置img高度改变时 宽度也改变
    self.backImg.userInteractionEnabled = YES;
    //裁剪
    self.backImg.clipsToBounds = YES;
    [self.collectionView addSubview:self.backImg];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.backImg addGestureRecognizer:tap];
    
    self.topJianBian = [[UIImageView alloc] initWithFrame:CGRectMake(0, -HEIGTH / 4 - 40, WIDTH, HEIGTH / 4 + 40)];
    self.topJianBian.image = [UIImage imageNamed:@"Topjiabian"];
    [self.collectionView addSubview:self.topJianBian];
    
    //渐变色图片
    self.img = [[UIImageView alloc]initWithFrame:CGRectMake(0, -HEIGTH / 4 - 40, WIDTH, -HEIGTH / 4 - 40)];
    self.img.userInteractionEnabled = NO;
    self.img.image = [UIImage imageNamed:@"jiabian"];
    [self.collectionView addSubview:self.img];
    
    self.countryLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, -65, 300 , 40)];
    [self.collectionView addSubview:self.countryLabel];
    self.countryLabel.textColor = [UIColor colorWithRed:1 green:0.98 blue:1 alpha:1];
    self.countryLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:26];
    
    self.goCount = [[UILabel alloc]initWithFrame:CGRectMake(17, -25 ,300 , 20)];
    self.goCount.textColor = [UIColor colorWithRed:1 green:0.98 blue:1 alpha:1];
    self.goCount.font = [UIFont fontWithName:@"Helvetica-Bold" size:13];
    self.goCount.shadowColor = [UIColor colorWithRed:0.75 green:0.82 blue:0.76 alpha:1];
    [self.collectionView addSubview:self.goCount];
    
    self.photoCountLabel = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH - 70, -25, 60, 20)];
    self.photoCountLabel.textColor = [UIColor colorWithRed:1 green:0.98 blue:1 alpha:1];
    self.photoCountLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:13];
    self.photoCountLabel.shadowColor = [UIColor colorWithRed:0.75 green:0.82 blue:0.76 alpha:1];
    [self.collectionView addSubview:self.photoCountLabel];
    
    self.camearImg = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH - 102, -27, 22, 22)];
    [self.collectionView addSubview:self.camearImg];

}

#pragma mark - 准备数据
- (void)prepareData
{
    NSString *str = [NSString stringWithFormat:@"http://api.breadtrip.com/destination/place/%@/%@", self.hottest_sitesModel.type, self.hottest_sitesModel.valueId];
    [MZNetHandle getUrl:str cookie:nil result:^(id result) {
        
        self.dataDic = [NSDictionary dictionaryWithDictionary:result];
        self.dataArr = [MZRecommendModel transformWithArray:self.dataDic[@"hottest_sites"]];
        
        [self.backImg sd_setImageWithURL:[NSURL URLWithString:self.dataDic[@"hottest_places"][0][@"photo"]] placeholderImage:[UIImage imageNamed:@"TheMostBig"]];
        self.countryLabel.text = self.hottest_sitesModel.name;
        self.goCount.text = [self getLabelText];
        self.photoCountLabel.text = [NSString stringWithFormat:@"%.1f 万张", [self.dataDic[@"photo_count"] floatValue] / 10000];
        self.camearImg.image = [UIImage imageNamed:@"iconfont-xiangji@2x"];
        self.likeBtn.hidden = NO;
        self.shareBtn.hidden = NO;
        
        [self.collectionView reloadData];
        [self.HUB removeFromSuperview];
    }];
}

#pragma mark - collectionView协议方法
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MZRecommendPushCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"destinationPush" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor cyanColor];
    cell.tempModel = self.dataArr[indexPath.item];
    return cell;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArr.count;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    MZRecommendPushCollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
    header.backgroundColor = [UIColor colorWithRed:250 / 255. green:246 / 255. blue:232 / 255. alpha:1];
    [header.btnNotes addTarget:self action:@selector(notesAction) forControlEvents:UIControlEventTouchUpInside];
    return header;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    
    if (((MZRecommendModel *)self.dataArr[indexPath.item]).type.integerValue == 5) {
        
        MZRecommendLastViewController *rlVC = [[MZRecommendLastViewController alloc] init];
        
        rlVC.tempModel = self.dataArr[indexPath.item];
        
        [self.navigationController pushViewController:rlVC animated:YES];
        
    }
    
}

- (void)notesAction
{
    MZNiceNotesViewController *nnVC = [[MZNiceNotesViewController alloc] init];
    nnVC.tempModel = self.tempModel;
    [self.navigationController pushViewController:nnVC animated:YES];
}

#pragma mark - 背景图下滑改变宽高
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //获取当前偏移量
    CGFloat y = scrollView.contentOffset.y;
    if (y < - HEIGTH / 4 + 40) {
        CGRect frame = self.backImg.frame;
        frame.origin.y = y; //image 的frame不断往上偏移
        frame.size.height = -y;//collectionview向下偏移了多少 高度就增加多少
        self.backImg.frame = frame;
        self.img.frame = frame; //渐变色图片
        self.topJianBian.frame = frame;
    }
    //bar 将要出来时  显隐度一点点改变
    if (scrollView.contentOffset.y <= 0 && scrollView.contentOffset.y >= -64) {
        self.naviView.alpha = (64 + scrollView.contentOffset.y) / 64;
    }
    else if (scrollView.contentOffset.y > 0)
    {
        self.naviView.alpha = 1.0;
    }
    else
    {
        self.naviView.alpha = 0.0;
    }
}

#pragma mark - 下滑跳转页面
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (scrollView.contentOffset.y < - HEIGTH / 3 - 60) {
        
        MZRecommendPhotosViewController *photosVC = [[MZRecommendPhotosViewController alloc] init];
        photosVC.tempModel = self.hottest_sitesModel;
        [self presentViewController:photosVC animated:YES completion:^{
        }];
        
    }
}

#pragma mark - 轻拍方法
- (void)tapAction:(UITapGestureRecognizer *)tap
{
    MZRecommendPhotosViewController *photosVC = [[MZRecommendPhotosViewController alloc] init];
    photosVC.tempModel = self.hottest_sitesModel;
    [self presentViewController:photosVC animated:YES completion:^{
    }];
}

#pragma mark - 收藏方法 登录
- (void)likeAction:(UIButton *)sender
{
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"judge"] == NO) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请先登录,才能收藏" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            
            landingViewController *login = [[landingViewController alloc] init];
            [self.navigationController pushViewController:login animated:YES];
            
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"judge"];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:okAction];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:nil];
        
    } else {
        
        if (self.isLake == NO) {
            
            self.isLake = YES;
            MuDiDi *mudidi = [NSEntityDescription insertNewObjectForEntityForName:@"MuDiDi" inManagedObjectContext:self.manager.managedObjectContext];
            mudidi.name = self.tempModel.name;
            mudidi.cover = self.tempModel.cover;
            mudidi.rating = self.tempModel.rating;
            mudidi.type = self.tempModel.type;
            mudidi.valueId = self.tempModel.valueId;
            mudidi.visited_count = self.tempModel.visited_count;
            [self.manager saveContext];
            [self.likeBtn setBackgroundImage:[UIImage imageNamed:@"redHeart"] forState:UIControlStateNormal];
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"收藏成功" preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alert animated:YES completion:nil];
            [self performSelector:@selector(delayDismiss) withObject:alert afterDelay:1];
            
        }else
        {
            self.isLake = NO;
            for (MuDiDi *mudidi in self.coreDataArr) {
                
                if ([mudidi.name isEqualToString:self.tempModel.name]) {
                    
                    [self.manager.managedObjectContext deleteObject:mudidi];
                }
            }
            [self.manager saveContext];
            [self.likeBtn setBackgroundImage:[UIImage imageNamed:@"whiteHeart"] forState:UIControlStateNormal];
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"取消收藏" preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alert animated:YES completion:nil];
            [self performSelector:@selector(delayDismiss) withObject:alert afterDelay:1];
        }
    }
}

#pragma mark - 分享
- (void)shareAction
{
    UIImageView *img = [[UIImageView alloc] init];
    img.frame = CGRectMake(100, 100, 100, 100);
    [img sd_setImageWithURL:[NSURL URLWithString:self.dataDic[@"share_args"][@"default"][@"shr_image"]] placeholderImage:[UIImage imageNamed:@""]];
    
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"5661bb71e0f55a4f60003bca"
                                      shareText:[NSString stringWithFormat:@"「%@」\n%@",self.dataDic[@"share_args"][@"default"][@"shr_text"], self.dataDic[@"share_args"][@"default"][@"shr_url"]]
                                     shareImage:img.image
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToWechatSession,UMShareToQQ,UMShareToTencent,UMShareToWechatTimeline,UMShareToQzone,UMShareToQQ,UMShareToRenren,UMShareToDouban,UMShareToEmail,UMShareToSms,UMShareToFacebook,UMShareToTwitter,nil]
                                       delegate:nil];
}

- (void)delayDismiss
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.hidden = NO;
    self.navigationController.navigationBar.hidden = NO;
}

- (void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSString *)getLabelText
{
    NSString *text = nil;
    if (([self.hottest_sitesModel.visited_count integerValue]) < 10000 && ([self.hottest_sitesModel.wish_to_go_count integerValue]) < 10000) {
        
        text = [NSString stringWithFormat:@"%@ 去过 / %@ 喜欢", self.hottest_sitesModel.visited_count, self.hottest_sitesModel.wish_to_go_count];
    }
    else if(([self.hottest_sitesModel.visited_count integerValue]) > 10000 && ([self.hottest_sitesModel.wish_to_go_count integerValue]) < 10000){
        
        text = [NSString stringWithFormat:@"%.1f 万去过 / %@ 喜欢", [self.hottest_sitesModel.visited_count floatValue] / 10000, self.hottest_sitesModel.wish_to_go_count];
    }
    else if (([self.hottest_sitesModel.visited_count integerValue]) > 10000 && ([self.hottest_sitesModel.wish_to_go_count integerValue]) > 10000){
        
        text = [NSString stringWithFormat:@"%.1f 万去过 / %.1f 万喜欢", [self.hottest_sitesModel.visited_count floatValue] / 10000, [self.hottest_sitesModel.wish_to_go_count floatValue] / 10000];
    }
    else
    {
        text = [NSString stringWithFormat:@"%@ 去过 / %.1f 万喜欢", self.hottest_sitesModel.visited_count, [self.hottest_sitesModel.wish_to_go_count floatValue] / 10000];
    }
    return text;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
